﻿//	Copyright (c) 2012 Jonathan Loe
//
//	MIT license (http://en.wikipedia.org/wiki/MIT_License)
//
//	Permission is hereby granted, free of charge, to any person obtaining a copy
//	of this software and associated documentation files (the "Software"), to deal
//	in the Software without restriction, including without limitation the rights 
//	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
//	of the Software, and to permit persons to whom the Software is furnished to do so, 
//	subject to the following conditions:
//
//	The above copyright notice and this permission notice shall be included in all 
//	copies or substantial portions of the Software.
//
//	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 
//	INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
//	PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE 
//	FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
//	ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

using System;
using System.Collections.Generic;
using System.Data.Linq.Mapping;
using System.Linq;
using System.Text;
using System.Transactions;

using Ordinaire.Db;
using Ordinaire.Security.Data;
using Ordinaire.Taxonomy;

namespace Ordinaire.Security
{
    /// <summary>
    /// Provides authorisation mechanism using database.
    /// </summary>
    public class DbAuthorisation : DataAccessEntity, IAuthorisation
    {
        #region Variables

        /// <summary>
        /// Instance of Ordinaire.Taxonomy.Taxonomist used as a helper.
        /// </summary>
        private Taxonomist<Role, RoleData> helper;

        /// <summary>
        /// Admin role.
        /// </summary>
        private Role adminRole;

        #endregion

        #region Constructor

        /// <summary>
        /// Returns new instance of Ordinaire.Security.DbAuthorisation.
        /// </summary>
        public DbAuthorisation()
        {
            helper = new Taxonomist<Role, RoleData>();
        }

        #endregion

        #region Property methods

        /// <summary>
        /// Gets the admin role.
        /// </summary>
        public Role AdminRole
        {
            get
            {
                if (this.adminRole == null)
                {
                    this.adminRole = GetAdminRole();
                }
                return this.adminRole;
            }
        }

        #endregion

        /// <summary>
        /// Assigns a role to a specified username along with the user who assigns this.
        /// </summary>
        /// <param name="username">designated username with the new role</param>
        /// <param name="role">the role</param>
        /// <param name="who">who assigns this</param>
        /// <returns>true if assignment is successful, else false</returns>
        public bool AssignRole(string username, Role role, User who)
        {
            if (String.IsNullOrEmpty(username))
            {
                throw new ArgumentException("username");
            }

            if (role == null)
            {
                throw new ArgumentNullException("role");
            }

            if (who == null)
            {
                throw new ArgumentNullException("who");
            }

            // Checks if both username and role have been assigned
            bool isAssigned = IsAssigned(username, role);
            if (isAssigned)
            {
                return false;
            }

            try
            {
                UserRole userRole  = new UserRole();
                userRole.UserId    = username;
                userRole.RoleId    = role.Id;
                userRole.CreatedBy = who.Id;

                Context.UserRoles.InsertOnSubmit(userRole);
                Context.SubmitChanges();

                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// Creates new role with specified name.
        /// </summary>
        /// <param name="name">role name</param>
        /// <param name="who">user who creates</param>
        /// <param name="parent">parent role</param>
        /// <returns>new instance of Ordinaire.Security.Role</returns>
        public Role CreateRole(string name, User who, Role parent = null)
        {
            return CreateRole(name, who.Id, parent);
        }

        /// <summary>
        /// Creates new role with specified name.
        /// </summary>
        /// <param name="name">role name</param>
        /// <param name="who">userid who creates</param>
        /// <param name="parent">parent role</param>
        /// <returns>new instance of Ordinaire.Security.Role</returns>
        public Role CreateRole(string name, string creatorId, Role parent = null)
        {
            if (String.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException("name");
            }

            if (creatorId == null)
            {
                throw new ArgumentNullException("creatorId");
            }

            if (parent == null)
            {
                parent = AdminRole;
            }

            Ordinaire.Security.Role exist = GetRoleByName(name, parent);
            if (exist != null)
            {
                return null;
            }

            try
            {
                RoleData data = new RoleData();
                data.Name      = name.CapitaliseFirstLetter();
                data.CreatedBy = creatorId;
                data.ParentId  = parent.Id;

                Context.Roles.InsertOnSubmit(data);
                Context.SubmitChanges();

                return data.ToRole();
            }
            catch (Exception)
            {
                return null;
            }
        }

        /// <summary>
        /// Returns role with the specifid id.
        /// </summary>
        /// <param name="id">role id</param>
        /// <returns>Ordinaire.Security.Role instance</returns>
        public Role GetRoleById(int id)
        {
            if (id == 0)
            {
                throw new ArgumentNullException("id");
            }

            return helper.Get(id);
        }

        /// <summary>
        /// Returns role with the specified role name.
        /// </summary>
        /// <param name="name">role name</param>
        /// <param name="parent">parent role</param>
        /// <returns>new instance of Ordinaire.Security.Role</returns>
        public Role GetRoleByName(string name, Role parent = null)
        {
            if (String.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException("name");
            }

            int parentId = (parent == null) ? 0 : parent.Id;
            List<Role> roles = helper.GetChildrenOfName(parentId, name);
            if (roles == null || roles.Count == 0)
            {
                return null;
            }

            return roles[0];
        }

        /// <summary>
        /// Returns list of roles assigned for the specified username.
        /// </summary>
        /// <param name="username">username</param>
        /// <returns>list of roles</returns>
        public List<Role> GetRoles(string username)
        {
            if (String.IsNullOrEmpty(username))
            {
                throw new ArgumentNullException("username");
            }

            var getUserRoles = from ur in Context.UserRoles
                               where ur.UserId == username
                               select ur.RoleId;
            int[] roleIds = getUserRoles.ToArray<int>();
            return helper.Get(roleIds);
        }

        /// <summary>
        /// Returns a value indicating whether both username and role are already assigned.
        /// </summary>
        /// <param name="username">the username</param>
        /// <param name="role">the corresponding role</param>
        /// <returns>true if they are already assigned, else false</returns>
        public bool IsAssigned(string username, Role role)
        {
            if (String.IsNullOrEmpty(username))
            {
                throw new ArgumentNullException("username");
            }

            if (role == null)
            {
                throw new ArgumentNullException("role");
            }

            var getAssignment = from ur in Context.UserRoles
                                where ur.UserId == username && ur.RoleId == role.Id
                                select ur;
            UserRole data = getAssignment.SingleOrDefault();
            return (data == null) ? false : true;
        }

        /// <summary>
        /// Clear and creates list of fresh role(s).
        /// </summary>
        /// <param name="names">list of new role names</param>
        /// <param name="creatorId">userid who creates</param>
        /// <returns>list of created roles</returns>
        public List<Role> Setup(string[] names, string creatorId)
        {
            List<Role> roles = new List<Role>();
            if (names == null || names.Length == 0)
            {
                return roles;
            }

            if (String.IsNullOrEmpty(creatorId))
            {
                throw new ArgumentNullException("creatorId");
            }

            using (OContext context = Context)
            {
                // Clear table and create new roles
                using (TransactionScope transaction = new TransactionScope())
                {
                    string truncate = String.Format("truncate table [{0}]", (new RoleData()).AttributeName<TableAttribute>());
                    context.ExecuteCommand(truncate);

                    foreach (string name in names)
                    {
                        RoleData data  = new RoleData();
                        data.Name      = name;
                        data.CreatedBy = creatorId;

                        context.Roles.InsertOnSubmit(data);
                        roles.Add(data.ToRole());
                    }

                    context.SubmitChanges();
                    transaction.Complete();
                    return roles;
                }
            }
        }

        #region Protected methods

        /// <summary>
        /// Returns administrator role.
        /// </summary>
        /// <returns>new instance of Ordinaire.Security.Role</returns>
        protected Role GetAdminRole()
        {
            List<Role> roots = helper.GetRoots();
            if (roots.Count > 1)
            {
                throw ExceptionFactory.Create<OException>(ExceptionMessage.MultipleAdminRolesFound);
            }
            return roots[0];
        }

        #endregion
    }
}
